import React, { useEffect } from 'react';
import { NavigateFunction, useNavigate } from 'react-router-dom';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';

import { reqLogin } from '../../api';
import userUnit from '../../utils/memory_utils';
import userStore from '../../utils/storage_utils';

import './index.less';
import logo from '../../assets/images/logo.png';


type UserInfo = {
    username: string;
    password: string;
};
type FinishFailed = {
    values: UserInfo;
    errorFields: unknown[];
    outOfDate: boolean;
};
type ResponseType = {
    status: number;
    data: ResponseDataSucess | ResponseDataFailure;
};
type ResponseDataSucess = {
    status: 0;
    data: unknown;
};
type ResponseDataFailure = {
    status: 1;
    msg: string;
};

enum ResponseStatus {
    sucess,
    failure,
    sucessStart = 200,
    sucessEnd = 299
}

// 登录的路由组件
const Login: React.FC = () => {
    const navigate: NavigateFunction = useNavigate();
    const onFinish = async (user: UserInfo): Promise<void> => {
        const { status, data }: ResponseType = await reqLogin(user.username, user.password);
        let errMsg: string = '请求失败!';
        if (status >= ResponseStatus.sucessStart && status <= ResponseStatus.sucessEnd) {
            const { status } = data as ResponseType['data'];
            if (status === ResponseStatus.sucess) {
                const result = (data as ResponseDataSucess).data as (UserInfo & Record<string, unknown>);
                userStore.saveUser(result);
                userUnit.isNotLogin = false;
                userUnit.user = result;
                message.success('登录成功!');
                navigate('/admin');
                return;
            }
            if (status === ResponseStatus.failure) errMsg = (data as ResponseDataFailure).msg;
        }
        message.error(errMsg);
    };
    const onFinishFailed = ({ values, errorFields, outOfDate }: FinishFailed): void => {
        console.log(values, errorFields, outOfDate, '检查失败');
    };
    const handleAsyncValid = (_: unknown, value: string): Promise<string | void> => {
        let msg: string = '';
        if (!value) {
            msg = '密码必须输入!';
        } else if (value.length < 4) {
            msg = '密码长度不能小于4位!';
        } else if (value.length > 12) {
            msg = '密码长度不能大于12位!';
        } else if (!/^\w+$/.test(value)) {
            msg = '密码必须英文、数字或下划线组成!';
        }
        return !msg ? Promise.resolve() : Promise.reject(new Error(msg));
    };
    useEffect((): void => {
        if (userUnit.isNotLogin) return;
        navigate('/admin');
    }, [navigate]);
    return (
        <div className="login">
            <header className="login-header">
                <img src={logo} alt="logo" />
                <h1>React项目: 后台管理系统</h1>
            </header>
            <section className="login-content">
                <h2>用户登录</h2>
                <div>
                    <Form
                        name="normal_login"
                        className="login-form"
                        /* initialValues={{
                            username: 'admin',
                            password: 'admin'
                        }} */
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                    >
                        <Form.Item
                            name="username"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入您的用户名！'
                                },
                                {
                                    min: 4,
                                    message: '用户名至少4位!'
                                },
                                {
                                    max: 12,
                                    message: '用户名不能超过12位!'
                                },
                                {
                                    pattern: /^\w+$/,
                                    message: '用户名必须是英文、数字或下划线组成'
                                }
                            ]}
                        >
                            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入账号" />
                        </Form.Item>
                        <Form.Item
                            name="password"
                            rules={[
                                {
                                    validator: handleAsyncValid
                                }
                            ]}
                        >
                            <Input
                                prefix={<LockOutlined className="site-form-item-icon" />}
                                type="password"
                                placeholder="请输入密码"
                            />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" className="login-form-button">登录</Button>
                        </Form.Item>
                    </Form>
                </div>
            </section>
        </div>
    );
};

export default Login;